<template>
  <div class="role-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>角色管理</span>
          <el-button type="primary" @click="handleCreate" v-if="hasPermission('role:create')">
            <el-icon><Plus /></el-icon>
            新增角色
          </el-button>
        </div>
      </template>

      <!-- 搜索和筛选 -->
      <div class="search-form">
        <el-form :model="searchForm" inline>
          <el-form-item label="搜索">
            <el-input
              v-model="searchForm.search"
              placeholder="角色名称/描述"
              clearable
              @keyup.enter="handleSearch"
              style="width: 250px"
            />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="全部状态" clearable>
              <el-option label="激活" value="ACTIVE" />
              <el-option label="禁用" value="INACTIVE" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 角色列表 -->
      <el-table
        v-loading="loading"
        :data="roleList"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="角色名称" width="150" />
        <el-table-column prop="description" label="描述" />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="用户数" width="100">
          <template #default="{ row }">
            {{ row._count?.userRoles || 0 }}
          </template>
        </el-table-column>
        <el-table-column label="权限数" width="100">
          <template #default="{ row }">
            {{ row._count?.rolePermissions || 0 }}
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="320" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button
                size="small"
                @click="handleEdit(row)"
                v-if="hasPermission('role:update')"
              >
                编辑
              </el-button>
              <el-button
                size="small"
                type="success"
                @click="handleAssignPermissions(row)"
                v-if="hasPermission('role:update')"
              >
                分配权限
              </el-button>
              <el-button
                size="small"
                :type="row.status === 'ACTIVE' ? 'danger' : 'success'"
                @click="handleToggleStatus(row)"
                v-if="hasPermission('role:update')"
              >
                {{ row.status === 'ACTIVE' ? '禁用' : '启用' }}
              </el-button>
              <el-button
                size="small"
                type="danger"
                @click="handleDelete(row)"
                v-if="hasPermission('role:delete')"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

                  <!-- 分页 -->
            <div class="pagination">
              <el-pagination
                v-model:current-page="pagination.page"
                v-model:page-size="pagination.limit"
                :page-sizes="[10, 20, 50, 100]"
                :total="pagination.total"
                layout="total, sizes, prev, pager, next, jumper"
                @change="handlePaginationChange"
              />
            </div>
    </el-card>

    <!-- 角色表单对话框 -->
    <el-dialog
      v-model="formDialogVisible"
      :title="isEdit ? '编辑角色' : '新增角色'"
      width="600px"
      :before-close="handleFormDialogClose"
    >
      <el-form
        ref="formRef"
        :model="roleForm"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input
            v-model="roleForm.name"
            placeholder="请输入角色名称"
          />
        </el-form-item>

        <el-form-item label="角色描述" prop="description">
          <el-input
            v-model="roleForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入角色描述"
          />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-select v-model="roleForm.status" placeholder="请选择状态">
            <el-option label="激活" value="ACTIVE" />
            <el-option label="禁用" value="INACTIVE" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleFormDialogClose">取消</el-button>
          <el-button type="primary" @click="handleFormSubmit" :loading="formLoading">
            {{ isEdit ? '更新' : '创建' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 权限分配对话框 -->
    <el-dialog
      v-model="permissionDialogVisible"
      title="分配权限"
      width="600px"
    >
      <el-tree
        ref="permissionTreeRef"
        :data="permissionTree"
        :props="{ label: 'name', children: 'children' }"
        show-checkbox
        node-key="id"
        :default-checked-keys="selectedPermissions"
        :check-strictly="false"
        default-expand-all
      >
        <template #default="{ node, data }">
          <div class="tree-node">
            <span class="node-label">{{ data.name }}</span>
            <span v-if="data.description && data.description !== data.name" class="node-description">({{ data.description }})</span>
            <span v-if="data.code && data.code !== data.name" class="node-code">[{{ data.code }}]</span>
          </div>
        </template>
      </el-tree>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="permissionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSavePermissions" :loading="permissionLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Plus, Search, Refresh } from '@element-plus/icons-vue'
import { roleApi, permissionApi } from '@/api'
import { useUserStore } from '@/stores/user'
import type { Role } from '@/types'
import { formatDate } from '@/utils/format'

const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const roleList = ref<Role[]>([])
const searchForm = reactive({
  search: '',
  status: ''
})

const pagination = reactive({
  page: 1,
  limit: 20,
  total: 0
})

// 角色表单相关
const formDialogVisible = ref(false)
const formLoading = ref(false)
const formRef = ref<FormInstance>()
const isEdit = ref(false)
const editingRoleId = ref<number | null>(null)

const roleForm = reactive({
  name: '',
  description: '',
  status: 'ACTIVE'
})

// 表单验证规则
const formRules: FormRules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 50, message: '角色名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '角色描述不能超过 200 个字符', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 权限分配相关
const permissionDialogVisible = ref(false)
const permissionLoading = ref(false)
const permissionTree = ref([])
const selectedPermissions = ref<number[]>([])
const currentRole = ref<Role | null>(null)
const permissionTreeRef = ref()

// 权限检查
const hasPermission = (permission: string) => {
  return userStore.hasPermission(permission)
}

// 获取角色列表
const fetchRoles = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      limit: pagination.limit,
      ...searchForm
    }
    const response = await roleApi.getRoles(params)
    // 根据实际后端返回的数据结构进行调整
    roleList.value = response.data.data
    pagination.total = response.data.pagination.total
  } catch (error) {
    ElMessage.error('获取角色列表失败')
  } finally {
    loading.value = false
  }
}

// 获取权限树
const fetchPermissionTree = async () => {
  try {
    const response = await permissionApi.getTree()
    console.log('权限树原始数据:', response.data)
    
    // 转换数据结构为标准的树形结构
    const treeData = response.data.tree.map((module: any) => ({
      id: `module-${module.module}`,
      name: module.module,
      children: module.permissions.map((permission: any) => ({
        id: permission.id,
        name: permission.name,
        code: permission.code,
        description: permission.description,
        module: module.module,
        roleCount: permission.roleCount
      }))
    }))
    
    console.log('转换后的权限树数据:', treeData)
    permissionTree.value = treeData
  } catch (error) {
    console.error('获取权限树失败:', error)
    ElMessage.error('获取权限树失败')
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchRoles()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    search: '',
    status: ''
  })
  pagination.page = 1
  fetchRoles()
}

// 分页处理
const handlePaginationChange = (page: number, size: number) => {
  pagination.page = page
  pagination.limit = size
  fetchRoles()
}

// 新增角色
const handleCreate = () => {
  isEdit.value = false
  editingRoleId.value = null
  resetRoleForm()
  formDialogVisible.value = true
}

// 编辑角色
const handleEdit = (row: Role) => {
  isEdit.value = true
  editingRoleId.value = row.id
  loadRoleData(row)
  formDialogVisible.value = true
}

// 分配权限
const handleAssignPermissions = async (row: Role) => {
  currentRole.value = row
  permissionDialogVisible.value = true
  
  try {
    // 获取角色当前权限
    const response = await roleApi.getRolePermissions(row.id)
    console.log('角色权限数据:', response.data)
    selectedPermissions.value = response.data.permissions.map(p => p.id)
    console.log('选中的权限ID:', selectedPermissions.value)
  } catch (error) {
    console.error('获取角色权限失败:', error)
    ElMessage.error('获取角色权限失败')
  }
}

// 保存权限分配
const handleSavePermissions = async () => {
  if (!currentRole.value || !permissionTreeRef.value) return
  
  try {
    permissionLoading.value = true
    const checkedKeys = permissionTreeRef.value.getCheckedKeys()
    const halfCheckedKeys = permissionTreeRef.value.getHalfCheckedKeys()
    const allKeys = [...checkedKeys, ...halfCheckedKeys]
    
    console.log('选中的权限:', checkedKeys)
    console.log('半选中的权限:', halfCheckedKeys)
    console.log('所有权限:', allKeys)
    
    // 过滤掉模块ID，只保留权限ID
    const permissionIds = allKeys.filter(key => typeof key === 'number')
    
    console.log('要分配的权限ID:', permissionIds)
    
    await roleApi.assignPermissions(currentRole.value.id, permissionIds)
    ElMessage.success('权限分配成功')
    permissionDialogVisible.value = false
    fetchRoles() // 刷新列表
  } catch (error) {
    console.error('权限分配失败:', error)
    ElMessage.error('权限分配失败')
  } finally {
    permissionLoading.value = false
  }
}

// 切换状态
const handleToggleStatus = async (row: Role) => {
  try {
    const newStatus = row.status === 'ACTIVE' ? 'INACTIVE' : 'ACTIVE'
    const action = newStatus === 'ACTIVE' ? '启用' : '禁用'
    
    await ElMessageBox.confirm(
      `确定要${action}角色 "${row.name}" 吗？`,
      `确认${action}`,
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await roleApi.updateRole(row.id, { status: newStatus })
    ElMessage.success(`${action}成功`)
    fetchRoles()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

// 删除角色
const handleDelete = async (row: Role) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除角色 "${row.name}" 吗？此操作不可恢复！`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await roleApi.deleteRole(row.id)
    ElMessage.success('删除成功')
    fetchRoles()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 状态相关
const getStatusType = (status: string): 'success' | 'warning' | 'danger' | 'info' => {
  const statusMap: Record<string, 'success' | 'warning' | 'danger' | 'info'> = {
    ACTIVE: 'success',
    INACTIVE: 'warning'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    ACTIVE: '激活',
    INACTIVE: '禁用'
  }
  return statusMap[status] || status
}

// 重置角色表单
const resetRoleForm = () => {
  Object.assign(roleForm, {
    name: '',
    description: '',
    status: 'ACTIVE'
  })
}

// 加载角色数据到表单
const loadRoleData = (role: Role) => {
  Object.assign(roleForm, {
    name: role.name,
    description: role.description || '',
    status: role.status
  })
}

// 处理表单对话框关闭
const handleFormDialogClose = () => {
  formDialogVisible.value = false
  resetRoleForm()
}

// 提交表单
const handleFormSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    formLoading.value = true
    
    const submitData = {
      name: roleForm.name,
      description: roleForm.description,
      status: roleForm.status as 'ACTIVE' | 'INACTIVE'
    }
    
    if (isEdit.value && editingRoleId.value) {
      await roleApi.updateRole(editingRoleId.value, submitData)
      ElMessage.success('角色更新成功')
    } else {
      await roleApi.createRole(submitData)
      ElMessage.success('角色创建成功')
    }
    
    formDialogVisible.value = false
    fetchRoles()
  } catch (error) {
    console.error('提交失败:', error)
  } finally {
    formLoading.value = false
  }
}

// 初始化
onMounted(() => {
  fetchRoles()
  fetchPermissionTree()
})
</script>

<style scoped>
.role-list {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.action-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
}

.action-buttons .el-button {
  margin: 0;
  flex-shrink: 0;
}

.tree-node {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.node-label {
  font-weight: 500;
  color: #303133;
}

.node-description {
  color: #909399;
  font-size: 12px;
}

.node-code {
  color: #409eff;
  font-size: 11px;
  background-color: #f0f9ff;
  padding: 1px 4px;
  border-radius: 3px;
  font-family: 'Courier New', monospace;
}
</style> 